/* SentenceController.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2009/8/7 �U�� 8:33:48 , Created by robbiecheng
}}IS_NOTE

Copyright (C) 2009 Potix Corporation. All Rights Reserved.

{{IS_RIGHT
	This program is distributed under GPL Version 2.0 in the hope that
	it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
 */
package org.corpus.english.controller;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.corpus.english.model.Article;
import org.corpus.english.model.ArticleHome;
import org.corpus.english.model.Sentence;
import org.corpus.english.model.SentenceCategoryData;
import org.corpus.english.model.SentenceCategoryDataHome;
import org.corpus.english.model.SentenceHome;
import org.corpus.english.model.SentenceQuery;
import org.corpus.english.model.SentenceSourceData;
import org.corpus.english.model.SentenceSourceDataHome;
import org.corpus.english.view.MyTreeNode;
import org.corpus.english.view.SentenceCategoryTreeNode;
import org.corpus.english.view.SentenceSourceRootNode;
import org.corpus.english.view.SentenceSourceTreeNode;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zk.ui.event.SelectionEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Html;
import org.zkoss.zul.Tree;
import org.zkoss.zul.TreeModel;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treeitem;


/**
 * @author robbiecheng
 * 
 */
public class SentenceController extends GenericForwardComposer {
	private SentenceHome sentDao = new SentenceHome();
	private SentenceCategoryDataHome scdDao = new SentenceCategoryDataHome();
	private SentenceSourceDataHome ssdDao = new SentenceSourceDataHome();
	private ArticleHome artDao = new ArticleHome();
	private Sentence currentSent =  new Sentence();
	private Article currentArticle = artDao.findById(1);
	private String selectedWord;	

	public void doBeforeComposeChildren(Component comp){
		if (Executions.getCurrent().getParameter("id") != null){
			String sentId = Executions.getCurrent().getParameter("id");
			currentSent = sentDao.findById(Integer.parseInt(sentId));
			comp.getPage().setVariable("current", currentSent);
		}
	}
	
	public List getAllSentences(){
		return sentDao.findByExample(new Sentence());
	}
	
	public Article getCurrentArticle() {
		return currentArticle;
	}
	
	//get article
	public void onChange$article(){
		artDao.merge(currentArticle);
	}
	
	//save article
	public void onClick$saveArticle(){
		artDao.merge(currentArticle);
		UpdateManager.showSaveSucessfulMessage();
	}
	
	//save selected word
	private Button transfer;
	public void onSelection$html(SelectionEvent evt){
		selectedWord = evt.getSelectedText();
		enableTransferAndSWBtns();
	}

	private void enableTransferAndSWBtns() {
		transfer.setDisabled(false);
		sw.setDisabled(false);
	}
	
	//transfer to word input
	public void onClick$transfer(){
		if (selectedWord != null && !"".equals(selectedWord)) {
			UpdateManager.transferWord(selectedWord, currentSent.getContent());
			selectedWord = null;
			transfer.setDisabled(true);
		}
	}
	
	//insert a new sentence into writing and oral db
	private Button sw;
	public void onClick$sw(){
		if (selectedWord != null && !"".equals(selectedWord)) {
			Sentence sent = new Sentence();			
			Set categories = new HashSet();
			
			SentenceCategoryData wrting = scdDao.findById(SentenceCategoryDataHome.WRITING_DB_ID);
			SentenceCategoryData oral = scdDao.findById(SentenceCategoryDataHome.ORAL_DB_ID);
			categories.add(wrting);
			categories.add(oral);
			
			SentenceSourceData notfinished = ssdDao.findById(SentenceSourceDataHome.NOT_FINISHED_ID);
			
			sent.setContent(selectedWord.trim());
			sent.setHtml(selectedWord.trim());
			sent.setSentenceSourceData(notfinished);
			sent.setSentenceCategoryDatas(categories);
			
			sentDao.persist(sent);
			
			selectedWord = null;
			sw.setDisabled(true);
			UpdateManager.showSaveSucessfulMessage();
		}
	}
	
	//parse HTML tags
	public void onChange$html(InputEvent evt){
		String result = evt.getValue()!= null? evt.getValue()
				.replaceAll("\\</p\\>", "\n")
				.replaceAll("\\<.*?\\>", "")
				.replaceAll("\\&.*?;", " "):evt.getValue();
		currentSent.setContent(result);
	}

	/**
	 * @return the current
	 */
	public Sentence getCurrent() {
		return currentSent;
	}
	
	public String getSelectedWord() {
		return selectedWord;
	}
	
	//coere ui into bean
	public void onSelect$source(SelectEvent evt){
		currentSent.setSentenceSourceData((SentenceSourceData) ((SentenceSourceTreeNode)((Treeitem)evt.getReference()).getValue()).getValue());
	}
	//coere ui into bean
	public void onSelect$category(SelectEvent evt){
		Set selectedItems = ((Tree)evt.getTarget()).getSelectedItems();		
		HashSet categorys = new HashSet(0);
		for (Iterator iterator = selectedItems.iterator(); iterator.hasNext();) {
			categorys.add(((SentenceCategoryTreeNode)((Treeitem)iterator.next()).getValue()).getValue());
		}
		currentSent.setSentenceCategoryDatas(categorys);
	}
	//save into database
	private Tree category;
	private Tree source;
	public void onClick$save() throws InterruptedException {
		source.getSelectedItem();
		category.getSelectedItems();
		if (currentSent.getSentenceid() == 0)
			sentDao.persist(currentSent);
		else
			sentDao.merge(currentSent);
		UpdateManager.showSaveSucessfulMessage();
	}
	
	//clear data
	public void onClick$clear(Event evt) {
		UpdateManager.resetSentenceInput();
	}
	
	//show all selected categories
	private Html allCatesHtml;
	public void onClick$showAllCatesBtn(){
		String result = "";
		Set cates = currentSent.getSentenceCategoryDatas();
		for (Iterator iterator = cates.iterator(); iterator.hasNext();) {
			SentenceCategoryData cate = (SentenceCategoryData) iterator.next();
			result += (cate.getFullname() + ", ");
		}
		allCatesHtml.setContent(result);
	}
	
	//open all tree children
	public void onClick$open(Event evt){
		
		//load all tree children from database
		TreeModel model = category.getModel();
		List treeNodes = new LinkedList();
		List newTreeNodes = new LinkedList();
		
		treeNodes.addAll(((MyTreeNode)model.getRoot()).getChildren());
		do 
		{
			for (int i = 0; i < treeNodes.size(); i++) {
				MyTreeNode node = (MyTreeNode) treeNodes.get(i);
				node.readChildren();
				if (node.getChildCount() > 0)
					newTreeNodes.addAll(node.getChildren());
			}
			treeNodes.clear();
			treeNodes.addAll(newTreeNodes);
			newTreeNodes.clear();
		} while (treeNodes.size() != 0);
		
		List children = new LinkedList();		
		List newChildren = new LinkedList();
		children.addAll(((Treechildren)category.getChildren().get(0)).getChildren());		
		do
		{
			for (int i = 0;i < children.size(); i++)
			{
				//open tree child
				Treeitem item = (Treeitem)children.get(i);
				item.setOpen(true);				
				//find and save tree child				
				if (item.getChildren().size() > 1)
					newChildren.addAll(((Treechildren)item.getChildren().get(1)).getChildren());
			}
			children.clear();
			children.addAll(newChildren);
			newChildren.clear();
		} while (children.size() != 0);
	}
}
